<template>
  <pro-table
    ref="table"
    title="管理员列表"
    :request="getList"
    :columns="columns"
    :search="searchConfig"
    :pagination="paginationConfig"
    @selectionChange="handleSelectionChange"
  >
    <!-- 工具栏 -->
    <template #toolbar>
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="addVisible = true"
      >
        添加
      </el-button>
      <el-button type="primary" icon="el-icon-refresh" @click="refresh">
        刷新
      </el-button>
    </template>
    <template #operate="scope">
      <el-button
        size="mini"
        type="primary"
        @click="$router.push(`/admin/edit/${scope.row.id}`)"
      >
        Edit
      </el-button>

      <el-popconfirm title="Are you sure to delete this?" @confirm="delAdmin(scope.row.id)">
        <template #reference>
          <el-button size="mini" type="danger">Delete</el-button>
        </template>
      </el-popconfirm>
    </template>
  </pro-table>
  <el-dialog
    v-model="addVisible"
    title="新增管理员"
    width="380px"
  >
<!--    表单-->
    <el-form
      ref="ruleFormRef"
      :model="addForm.item"
      :rules="addForm.rules"
      label-width="120px"
      class="demo-ruleForm"
    >
     <el-form-item label="选择成员" prop="target">
        <el-select v-model="addForm.item.target" filterable placeholder="请选择成员">
          <el-option
            v-for="item in addSelect"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            :disabled="item.disabled"
          >
          </el-option>
        </el-select>
      </el-form-item>
     <el-form-item label="分配角色" prop="authorization">
       <el-radio-group v-model="addForm.item.authorization" size="large">
         <el-radio-button label="管理员"></el-radio-button>
         <el-radio-button label="超级管理员"></el-radio-button>
       </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addVisible = false">Cancel</el-button>
        <el-button type="primary" @click="submitForm('ruleFormRef')">Confirm</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { defineComponent, onMounted, reactive, ref, toRefs } from "vue";
import { getAdminList, getUserList } from "@/api/admin";
import { addAdmin, delAdmin } from "../../api/admin";
import { ElMessage } from "element-plus";

export default defineComponent({
  name: 'adminList',
  setup() {
    const state = reactive({
      addVisible: ref(false),
      addSelect: [],
      ruleFormRef: ref(),
      addForm: {
        item: {
          target: '',
          authorization: '管理员',
        },
        rules: {
          target: [
            {
              required: true,
              message: '请选择成员',
              trigger: 'change',
            },
          ],
          authorization: [
            {
              required: true,
              message: '请选择角色',
              trigger: 'change',
            },
          ],
        },
      },
      // 表格列配置，大部分属性跟el-table-column配置一样
      columns: [
        { type: 'selection' },
        { label: '序号', prop: 'id' },
        { label: '游戏ID', prop: 'nickname', sortable: true, width: 180 },
        { label: '氏族', prop: 'team' },
        { label: 'QQ', prop: 'qq' },
        { label: '角色', prop: 'authorization' },
        { label: '状态', prop: 'status' },
        {
          label: '操作',
          fixed: 'right',
          width: 180,
          align: 'left',
          tdSlot: 'operate', // 自定义单元格内容的插槽名称
        },
      ],
      // 搜索配置
      searchConfig: {
        labelWidth: '90px', // 必须带上单位
        inputWidth: '360px', // 必须带上单位
        fields: [
          {
            type: 'text',
            label: '游戏ID',
            name: 'nickname',
          },
          {
            label: '状态',
            name: 'status',
            type: 'select',
            options: [
              {
                name: '',
                value: '',
              },
              {
                name: '正常',
                value: 1,
              },
              {
                name: '冻结',
                value: 2,
              },
            ],
          },
          {
            label: '氏族',
            name: 'team',
            type: 'radio-button',
            options: [
              {
                name: '一团',
                value: 1,
              },
              {
                name: '二团',
                value: 2,
              },
              {
                name: '三团',
                value: 3,
              },
              {
                name: '四团',
                value: 4,
              },
            ],
          },
        ],
      },
      // 分页配置
      paginationConfig: {
        layout: 'total, prev, pager, next, sizes', // 分页组件显示哪些功能
        pageSize: 5, // 每页条数
        pageSizes: [5, 10, 15, 20, 50],
        style: { textAlign: 'left' },
      },
      selectedItems: [],
      batchDelete() {
        console.log(state.selectedItems)
      },
      // 选择
      handleSelectionChange(arr) {
        state.selectedItems = arr
      },
      // 请求函数
      async getList(params) {
        // params是从组件接收的，包含分页和搜索字段。
        const { data } = await getAdminList(params)
        // 必须要返回一个对象，包含data数组和total总数
        return {
          data: data.list,
          total: +data.total,
        }
      },
    })
    const table = ref(null)
    const refresh = () => {
      table.value.refresh()
      methods.getUserList()
    }
    const methods = {
      async getUserList() {
        let resp = await getUserList()
        let list = resp.data.list
        state.addSelect = list.map((item) => {
          return { value: item.id, label: '[ '+item.team+' ] '+item.nickname, disabled:item.disabled}
        })
      },
      submitForm(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            let resp = await addAdmin(state.addForm.item)
            if (resp.code !== 200) {
              ElMessage({
                message: resp.message || '服务器错误！',
                type: 'error',
              })
            } else {
              state.addVisible = false
              table.value.refresh()
              ElMessage({
                message: resp.message || 'ok',
                type: 'success',
              })
            }
          } else {
            return false
          }
        })
      },
      async delAdmin(aid) {
        let resp = await delAdmin(aid)
        if(resp.code !== 200){
          ElMessage({
            message: resp.message || '服务器错误！',
            type: 'error',
          })
        }else {
          table.value.refresh()
          ElMessage({
            message: resp.message || 'ok',
            type: 'success',
          })
        }
      },
    }
    onMounted(() => {
      methods.getUserList()
    })
    return { ...toRefs(state), refresh, table, ...methods }
  },
})
</script>
